﻿using cn.jpush.api;
using cn.jpush.api.push;
using cn.jpush.api.push.mode;
using cn.jpush.api.push.notification;
using cn.jpush.api.util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyPush
{
    public partial class MainForm : Form
    {
        private JPushClient client;
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
        }

        private void btnSendPush_Click(object sender, EventArgs e)
        {
            try
            {
                string sAppkey = tAppKey.Text;
                string sMasterSecret = tMasterSecret.Text;

                if (string.IsNullOrEmpty(sAppkey) || string.IsNullOrEmpty(sMasterSecret))
                    throw new Exception("请输入AppKey/MasterSecret!");
                this.client = new JPushClient(sAppkey, sMasterSecret);

                PushPayload pushPayload = new PushPayload();
                //平台
                pushPayload.platform = Platform.all();
                if (!cbAllPlatform.Checked)
                {
                    if (clbPlatform.CheckedItems.Count > 0)
                    {
                        pushPayload.platform.deviceTypes = new HashSet<string>();
                        for (int index = 0; index < clbPlatform.CheckedItems.Count; index++)
                        {
                            pushPayload.platform.deviceTypes.Add(clbPlatform.CheckedItems[index].ToString());
                        }
                    }
                    else
                        throw new Exception("请选择推送平台！");
                }
                //推送目标
                pushPayload.audience = Audience.all();
                if (!cbAllTarget.Checked)
                {
                    pushPayload.audience = tPushTarget.Tag as Audience;
                    if (pushPayload.audience == null)
                        throw new Exception("请输入推送目标！");
                }
                if (!cbNotify.Checked && !cbMsg.Checked)
                    throw new Exception("通知和消息至少选择一项！");
                //消息
                if (cbMsg.Checked)
                {
                    if (string.IsNullOrEmpty(tMsgContent.Text))
                        throw new Exception("请输入消息内容！");
                    pushPayload.message = cn.jpush.api.push.mode.Message.content(tMsgContent.Text);
                    pushPayload.message.setTitle(tMsgTitle.Text);
                    pushPayload.message.setContentType(tContentType.Text);
                    if (tMsgExtras.Tag != null)
                    {
                        Dictionary<string, object> extras = tMsgExtras.Tag as Dictionary<string, object>;
                        if (extras != null)
                        {
                            foreach (KeyValuePair<string, object> extra in extras)
                            {
                                string type = extra.Value.GetType().FullName;
                                switch (type)
                                {
                                    case "System.Boolean":
                                        pushPayload.message.AddExtras(extra.Key, Convert.ToBoolean(extra.Value));
                                        break;
                                    case "System.Int32":
                                        pushPayload.message.AddExtras(extra.Key, Convert.ToInt32(extra.Value));
                                        break;
                                    case "System.String":
                                        pushPayload.message.AddExtras(extra.Key, Convert.ToString(extra.Value));
                                        break;
                                }
                            }
                        }
                    }
                }
                //通知
                if (cbNotify.Checked)
                {
                    pushPayload.notification = new Notification();
                    if (string.IsNullOrEmpty(tContent.Text))
                        throw new Exception("请填写通知内容！");
                    pushPayload.notification.alert = tContent.Text;
                    pushPayload.notification.AndroidNotification = new cn.jpush.api.push.notification.AndroidNotification();
                    pushPayload.notification.AndroidNotification.setAlert(tContent.Text);
                    pushPayload.notification.AndroidNotification.setTitle(tNotifyTitleAndroid.Text);
                    if (tNotifyExtras.Tag != null)
                    {
                        Dictionary<string, object> extras = tNotifyExtras.Tag as Dictionary<string, object>;
                        if (extras != null)
                        {
                            foreach (KeyValuePair<string, object> extra in extras)
                            {
                                string type = extra.Value.GetType().FullName;
                                switch (type)
                                {
                                    case "System.Boolean":
                                        pushPayload.notification.AndroidNotification.AddExtra(extra.Key, Convert.ToBoolean(extra.Value));
                                        break;
                                    case "System.Int32":
                                        pushPayload.notification.AndroidNotification.AddExtra(extra.Key, Convert.ToInt32(extra.Value));
                                        break;
                                    case "System.String":
                                        pushPayload.notification.AndroidNotification.AddExtra(extra.Key, Convert.ToString(extra.Value));
                                        break;
                                }
                            }
                        }
                    }

                    pushPayload.notification.IosNotification = new cn.jpush.api.push.notification.IosNotification();
                    pushPayload.notification.IosNotification.setAlert(tContent.Text);
                    pushPayload.notification.IosNotification.incrBadge(1);
                    if (tNotifyExtras.Tag != null)
                    {
                        Dictionary<string, object> extras = tNotifyExtras.Tag as Dictionary<string, object>;
                        if (extras != null)
                        {
                            foreach (KeyValuePair<string, object> extra in extras)
                            {
                                string type = extra.Value.GetType().FullName;
                                switch (type)
                                {
                                    case "System.Boolean":
                                        pushPayload.notification.IosNotification.AddExtra(extra.Key, Convert.ToBoolean(extra.Value));
                                        break;
                                    case "System.Int32":
                                        pushPayload.notification.IosNotification.AddExtra(extra.Key, Convert.ToInt32(extra.Value));
                                        break;
                                    case "System.String":
                                        pushPayload.notification.IosNotification.AddExtra(extra.Key, Convert.ToString(extra.Value));
                                        break;
                                }
                            }
                        }
                    }
                }

                //options
                pushPayload.options = new Options() { time_to_live = 86400, apns_production = cbIOSPush.Checked };
                tJPushMessage.Text = pushPayload.ToJson();
                btnSendPush.Enabled = false;
                Utils.RunBackgroundWorker(backgroundWorkerMain, (s1, e1) =>
                {
                    try
                    {

                        MessageResult result = this.client.SendPush(pushPayload);
                        e1.Result = result;
                    }
                    catch (Exception ee)
                    {
                        e1.Result = ee.Message;
                    }
                }, (s2, e2) =>
                {
                    MessageResult result = e2.Result as MessageResult;
                    if (result == null || !result.isResultOK())
                        MessageBox.Show(string.Format("消息推送失败！{0}", e2.Result), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        MessageBox.Show("消息推送成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnSendPush.Enabled = true;
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void cbAllPlatform_CheckedChanged(object sender, EventArgs e)
        {
            clbPlatform.Enabled = !cbAllPlatform.Checked;
        }

        private void cbAllTarget_CheckedChanged(object sender, EventArgs e)
        {
            btnPushTarget.Enabled = !cbAllTarget.Checked;
            tPushTarget.Text = cbAllTarget.Checked ? "\"audience\":\"all\"" : "";
        }

        private void btnMsgExtras_Click(object sender, EventArgs e)
        {
            Dictionary<string, object> _extras = tMsgExtras.Tag as Dictionary<string, object>;
            using (ExtrasForm ef = new ExtrasForm(_extras))
            {
                if (ef.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    tMsgExtras.Tag = ef.Extras;
                    if (ef.Extras != null && ef.Extras.Count > 0)
                        tMsgExtras.Text = JsonTool.DictionaryToJson(ef.Extras);
                    else
                        tMsgExtras.Text = "";
                }
            }
        }

        private void btnPushTarget_Click(object sender, EventArgs e)
        {
            Audience audience = tPushTarget.Tag as Audience;
            using (PushTargetForm ptf = new PushTargetForm(audience))
            {
                if (ptf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    tPushTarget.Tag = ptf.Target;
                    if (ptf.Target != null)
                        tPushTarget.Text = "\"audience\":{" + JsonToolExt.DictionaryToJson(ptf.Target.dictionary) + "}";
                    else
                        tPushTarget.Text = "";
                }
            }
        }

        private void btnNotifyExtras_Click(object sender, EventArgs e)
        {
            Dictionary<string, object> _extras = tNotifyExtras.Tag as Dictionary<string, object>;
            using (ExtrasForm ef = new ExtrasForm(_extras))
            {
                if (ef.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    tNotifyExtras.Tag = ef.Extras;
                    if (ef.Extras != null && ef.Extras.Count > 0)
                        tNotifyExtras.Text = JsonTool.DictionaryToJson(ef.Extras);
                    else
                        tNotifyExtras.Text = "";
                }
            }
        }

        private void cbNotify_CheckedChanged(object sender, EventArgs e)
        {
            gbNotify.Enabled = cbNotify.Checked;
        }

        private void cbMsg_CheckedChanged(object sender, EventArgs e)
        {
            gbMsg.Enabled = cbMsg.Checked;
        }
    }
}
